# -*- coding: utf-8 -*-

import sip
sip.setapi('QString', 2)
sip.setapi('QStringList', 2)
sip.setapi('QVariant', 2)

from TimerThread import TimerThread
from PyQt4 import QtCore

#_______________________________________________________________________________
class CollectionTreeSortFilterController(QtCore.QObject):
    def __init__(self, server, model, view):
        QtCore.QObject.__init__(self)
        self.server_ctrl = server
        self.view = view
        self.model = model
        self.text_filter = ""
#        self.view.line_text.setPlaceholderText("search collection")
        self.view.button.setEnabled(False)
        self.server_ctrl.client_connected.connect(self.connect)
        self.view.header.sectionClicked.connect(self.sort_model)
        
    def connect(self, connected):
        if connected is True:
            self.timer = TimerThread(self.start_filter, True)
            self.view.button.setEnabled(True)
            self.view.line_text.returnPressed.connect(self.start_filter)
            self.view.line_text.textChanged.connect(self.start_timer)
    
    def start_filter(self):
        text = self.view.line_text.text().toUtf8()
        self.set_pattern(text)
        
    def start_timer(self):
        if self.timer.isRunning():
            self.timer.exit_()
            self.timer.start()
        else:
            self.timer.start()

    def set_pattern(self, pattern):
        if self.text_filter != str(pattern):
            self.text_filter = str(pattern)
            self.model.metadatadb.create_new_view(self.text_filter)
            self.model.insert_data()

    def sort_model(self, ignore):
        if self.model.data_order == "asc":
            self.model.data_order = "desc"
        else:
            self.model.data_order = "asc"
        self.model.metadatadb.create_new_view(self.text_filter)
        self.model.insert_data()